#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
    Garden Module here.

"""
import time, sys, json, wx, codecs, os
import threading, thread
from util import *
import config
import xml.parsers.expat
from captcha import readcaptcha
import cStringIO

class CallFunctionOnMainThread:
    def __init__(self, function):
        self.function = function

        self.cv = threading.Condition()
        self.result = None

    def __call__(self, *args):
        self.cv.acquire()

        wx.CallAfter(self._onMainThread, *args)

        self.cv.wait()
        self.cv.release()

        return self.result

    def _onMainThread(self, *args):
        try:
            self.result = self.function(*args)
        finally:
            pass
        
        self.cv.acquire()
        self.cv.notify()
        self.cv.release()

class MyDialog(wx.Dialog):
    def __init__(self, rcode):
        wx.Dialog.__init__(self, None, -1, u'输入验证码', size=(250,170))
        sizer_1 = wx.BoxSizer(wx.VERTICAL)
        self.emptybmp = wx.EmptyImage(140,50).ConvertToBitmap()
        self.sb_origin = wx.StaticBitmap(self, -1,self.emptybmp)
        req = httprequest.openurl('http://www.kaixin001.com/interface/regcreatepng.php',{'randnum':rcode, 'norect':'1'},'Get')
        stream = cStringIO.StringIO(req['data'])
        self.sb_origin.SetBitmap(wx.BitmapFromImage(wx.ImageFromStream(stream)))
        self.text = wx.TextCtrl(self, -1, size=(-1,-1))
        #label = wx.StaticText(self, -1, u'输入验证码')
        #sizer_1.Add(label, 0, wx.ALIGN_CENTER_HORIZONTAL| wx.ALL, 5)
        sizer_1.Add(self.sb_origin, 0, wx.ALIGN_CENTER_HORIZONTAL| wx.ALL, 5)
        sizer_1.Add(self.text, 0, wx.ALIGN_CENTER_HORIZONTAL| wx.ALL, 5)
        self.ok = wx.Button(self, wx.ID_OK, "OK")
        self.cancel = wx.Button(self, wx.ID_CANCEL, "Cancel")
        sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_2.Add(self.ok, 0, wx.ALIGN_CENTER_HORIZONTAL| wx.ALL, 5)
        sizer_2.Add(self.cancel, 0, wx.ALIGN_CENTER_HORIZONTAL| wx.ALL, 5)
        sizer_1.Add(sizer_2, 0, wx.ALIGN_CENTER_HORIZONTAL)
        self.SetSizer(sizer_1)

class Pane_garden( wx.Panel ):
    def __init__(self, parent):
        wx.Panel.__init__( self, parent )
        self.button_1 = wx.Button(self, -1, u"查看自家")
        self.button_3 = wx.Button(self, -1, u"干活喽")
        #self.button_4 = wx.Button(self, -1, u"两手一起抓")
        self.button_5 = wx.Button(self, -1, u"清空记录")
        self.button_stop = wx.Button(self, -1, u"停一停")
        self.gardenlog = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE|wx.TE_READONLY)

        self.jobsLB = wx.CheckListBox(self, -1, (-1,-1), (85,80), [])
        self.SBox_jobs = wx.StaticBox(self, -1, u"分配任务")
        self.SBox_jobs_sizer = wx.StaticBoxSizer(self.SBox_jobs, wx.VERTICAL)
        self.SBox_jobs_sizer.Add(self.jobsLB, 0, wx.ALIGN_CENTER_HORIZONTAL| wx.ALL, 2)
        self.Bind(wx.EVT_CHECKLISTBOX, self.Evt_jobsLB, self.jobsLB)

        self.Bind(wx.EVT_BUTTON, self.gardenRefresh, self.button_1)
        self.Bind(wx.EVT_BUTTON, self.doJobs, self.button_3)
        #self.Bind(wx.EVT_BUTTON, self.checkFriend, self.button_4)
        self.Bind(wx.EVT_BUTTON, self.clearlog, self.button_5)
        self.Bind(wx.EVT_BUTTON, self.stopRightNow, self.button_stop)

        sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_5 = wx.BoxSizer(wx.VERTICAL)
        sizer_5.Add(self.button_1, 0, wx.ALIGN_CENTER_HORIZONTAL| wx.ALL, 5)
        sizer_5.Add(self.button_3, 0, wx.ALIGN_CENTER_HORIZONTAL| wx.ALL, 5)
        sizer_5.Add(self.SBox_jobs_sizer, 0, wx.ALIGN_CENTER_HORIZONTAL| wx.ALL, 5)
        sizer_5.Add(self.button_stop, 0, wx.ALIGN_CENTER_HORIZONTAL| wx.ALL, 5)
        sizer_5.Add(self.button_5, 0, wx.ALIGN_CENTER_HORIZONTAL| wx.ALL, 5)

        sizer_2.Add(sizer_5, 0, wx.TOP|wx.BOTTOM|wx.ALIGN_CENTER_VERTICAL, 5)
        sizer_2.Add(self.gardenlog, 1, wx.EXPAND, 0)
        self.SetSizer(sizer_2)

        self.littlepool = []
        self.__set_properties()

    def __set_properties(self):
        list = [u'我的菜地',u'我的牧场',u'好友的菜地',u'好友的牧场']
        for i in list: self.jobsLB.Append(i)
        for i in config.global_jobs_list:
            self.jobsLB.Check(int(i))
    
    def stopRightNow(self, event):
        try:
            self.littlepool[0].stop()
        except:
            pass

    def checkFriend(self, event):
        if self.littlepool:
            self.logging(u'Working right now, 少安毋躁')
            return
        self.littlepool.append( threadCheckGarden(self,'checkFriend') )
        self.littlepool[0].start()

    def logging(self, text, timestamp = True, newline = True):
        output = ''
        if timestamp:
            output = output + '['+time.strftime('%m/%d %H:%M:%S')+'] '
        output = output + text
        if newline:
           output = output +'\n'
        self.gardenlog.AppendText(output)
        if config.global_logoption:
            logfile = codecs.open('garden_log.txt', 'a', 'utf-8')
            logfile.write(output)
            logfile.close()
           
    def clearlog(self, event):
        self.gardenlog.Clear()

    def Evt_jobsLB(self, event):
        index = event.GetSelection()
        if self.jobsLB.IsChecked(index):
            self.jobsLB.SetSelection(index)
        list = []
        config.global_jobs_list = [str(i) for i in range(self.jobsLB.GetCount()) if self.jobsLB.IsChecked(i)]

    def gardenRefresh(self, event):
        if self.littlepool:
            self.logging(u'Working right now, 少安毋躁')
            return
        self.littlepool.append( threadCheckGarden(self,'readMine') )
        self.littlepool[0].start()

    def doJobs(self, event):
        if self.littlepool:
            self.logging(u'Working right now, 少安毋躁')
            return
        self.littlepool.append( threadCheckGarden(self, config.global_jobs_list) )
        self.littlepool[0].start()
    
    def jumpdialog(self):
        rcode = getR()
        dialog = MyDialog(rcode)
        r = dialog.ShowModal()
        if r == wx.ID_OK:
            code = dialog.text.GetValue()
            dialog.Destroy()
            return {'rcode':rcode,'code':code.encode('UTF-8')}
        dialog.Destroy()

class threadCheckGarden(threading.Thread):
    def __init__(self, parent, action):
        self.friends_actionsList= [
                {
                    'action':u'浇水',
                    'url':'http://www.kaixin001.com/!house/!garden/water.php', 
                    'check': lambda item: int(item.find('water').text) < 3,
                    'method':'Get'
                    },
                {
                    'action':u'除草', 
                    'url':'http://www.kaixin001.com/!house/!garden/antigrass.php', 
                    'check': lambda item: item.find('grass').text == '1',
                    'method':'Post'
                    },
                {
                    'action':u'捉虫', 
                    'url':'http://www.kaixin001.com/!house/!garden/antivermin.php', 
                    'check': lambda item: item.find('vermin').text == '1',
                    'method':'Post'
                    }
                ]
        self.me_actionsList= [
                {
                    'action':u'浇水',
                    'url':'http://www.kaixin001.com/!house/!garden/water.php', 
                    'check': lambda item: int(item.find('water').text) < 5,
                    'method':'Get'
                    },
                {
                    'action':u'除草', 
                    'url':'http://www.kaixin001.com/!house/!garden/antigrass.php', 
                    'check': lambda item: item.find('grass').text == '1',
                    'method':'Post'
                    },
                {
                    'action':u'捉虫', 
                    'url':'http://www.kaixin001.com/!house/!garden/antivermin.php', 
                    'check': lambda item: item.find('vermin').text == '1',
                    'method':'Post'
                    }
                ]
        threading.Thread.__init__(self)
        self.event = threading.Event()
        self.event.clear()
        self.logging = parent.logging
        self.parent = parent        
        self.littlepool = parent.littlepool
        self.usercb = parent.GetParent().pane_setting.accountcb
        self.accountinfo = parent.GetParent().accountinfo
        self.action = action
        self.seeding = parent.GetParent().pane_setting.seedcb.IsEnabled()
        self.timeroption = parent.GetParent().pane_setting.timeroption.IsChecked()
        
        config.currentUser = self.usercb.GetValue()
        httprequest.__init__()

        if self.seeding:
            self.autoseedname = parent.GetParent().pane_setting.seedcb.GetValue()
            self.autoseedid = self.getseedid(self.autoseedname)
        if self.timeroption:
            self.timer = int( parent.GetParent().pane_setting.timerTC.GetValue() )
        else:
            self.timer = False
    def getseedid(self, seedname):
        seedidfile = ET.parse('seed.xml')
        seeds = seedidfile.findall('item')
        for elm in seeds:
            if elm.find('name').text == seedname:
                seedid = elm.find('seedid').text
                return seedid

    def logon(self):
        self.logging(u'登录帐号...', newline = False)
        self.logging(self.usercb.GetValue() + '...' ,timestamp = False, newline = False)
        login_result = self.accountinfo.login(self.usercb.GetValue())
        fail_count = 0
        while login_result not in [False,True]:
            captchacode = CallFunctionOnMainThread(self.parent.jumpdialog)
            param = captchacode()
            if param:
                param['url'] = '/home/'
                param['rpkey'] = ''
                param['invisible_mode'] = '0'
            else:
                param = {}
                fail_count += 1
            if fail_count > 3:
                login_result = False
            else:
                login_result = self.accountinfo.login(self.usercb.GetValue(), param)
        if login_result == True:
            self.logging(u'成功', timestamp = False)
            return True
        elif not login_result:
            self.logging(u'失败', timestamp = False)
            return False
                
    def run(self):
        while True:
            if self.check_if_stop():
                return
            if len(config.global_jobs_list) == 0 and self.action != 'readMine':
                self.logging(u'你想干啥？')
                if self.littlepool:
                    self.littlepool.pop()
                return
            if not self.logon():
                pass
            elif self.action == 'readMine':
                self.readMygarden()
                self.readMyranch()
                self.readMyfishing()
            else:
                if '0' in self.action:
                    self.runMygarden()
                if '1' in self.action:
                    self.runMyranch()
                if '2' in self.action:
                    self.friends_garden()
                if '3' in self.action:
                    self.friends_ranch()
            if self.check_if_stop():
                return
            if not self.timer:
                if logout():
                    self.logging(u'退出帐号')
                self.logging(u'Done!')
                self.littlepool.pop()
                return
            else:
                if logout():
                    self.logging(u'退出帐号')
                self.logging(u'等待'+str(self.timer)+u'分钟进行下一轮')
                self.event.wait(self.timer*60)
            
    def check_if_stop(self):
        if self.event.isSet():
            if logout():
                self.logging(u'退出帐号')
            self.logging(u'用户中断!')
            if self.littlepool:
                self.littlepool.pop()
            return True

    def readMygarden(self):
        if self.event.isSet():
            return
        try:
            self.logging(u'获取Verify...', newline = False)
            a = gardenVerify()
            self.logging(u'成功', timestamp = False)
        except:
            self.logging(u'失败', timestamp = False)
            return
        self.verify = a[0]
        self.myuid = a[1]
        self.logging(u'读取菜地信息...', newline = False)
        r = self.getconf_garden('0')
        if not r:
            self.logging(u'失败', timestamp = False)
            return
        else:
            self.logging(u'成功', timestamp = False)
        for elm in r.findall('account'):
            self.logging( elm.find('name').text + '('+self.myuid+')' + ' ' + elm.find('ranktip').text.replace('\n',''))
            self.logging( elm.find('cashtip').text + ' '+
                    u'魅力值'+ ' ' + elm.find('tcharms').text)
        for elm in r.findall('garden/item'):    #花园信息
            #self.smartc()
            #self.getpic()
            if elm.find('cropsid').text != '0':
                if elm.find('shared').text == '0':
                    self.logging(u'自留地' + ' ' + elm.find('name').text+' ', newline = False)
                else:
                    self.logging(u'爱心地' + ' ' + elm.find('name').text+' ', newline = False)
                if elm.find('water').text != '5':
                    self.logging(u'水量' + elm.find('water').text+' ', timestamp = False, newline = False)
                if elm.find('vermin').text == '1':
                    self.logging(u'有害虫 ', timestamp = False, newline = False)
                if elm.find('grass').text == '1':
                    self.logging ( u'有杂草 ', timestamp = False, newline = False)
                if elm.find('cropsstatus').text == '3':
                    self.logging(u'需犁地', timestamp = False)
                elif re.search(u"已枯死", elm.find('crops').text):
                    self.logging(u"已枯死", timestamp = False)
                elif elm.find('cropsstatus').text == '-1':
                    self.logging(u'已偷光', timestamp = False)
                elif re.search(u"距离收获", elm.find('crops').text):
                    self.logging( strip_html_tags(
                        re.search(u"(?P<output>距离收获.*)", elm.find('crops').text).group('output')
                        ), timestamp = False)
                else:
                    self.logging(strip_html_tags(elm.find('crops').text), timestamp = False)
            elif elm.find('status').text == '1':
                if elm.find('shared').text == '0':
                    self.logging( u'自留地 空地' )
                else:
                    self.logging( u'爱心地 空地' )
        if self.event.isSet():
            return
        shared = ''#self.getShared()
        if not len(shared):
            return
        for uid in shared:
            r = self.getconf_garden(uid)
            blove = [elm for elm in r.findall('garden/item') if elm.find('fuid').text == self.myuid]
            for elm in blove:
                self.logging(u'种在<'+shared[uid]+u'>家的<'+elm.find('name').text+'>', newline = False)
                if elm.find('water').text != '5':
                    self.logging(u'水量' + elm.find('water').text+' ', timestamp = False, newline = False)
                if elm.find('vermin').text == '1':
                    self.logging(u'有害虫 ', timestamp = False, newline = False)
                if elm.find('grass').text == '1':
                    self.logging ( u'有杂草 ', timestamp = False, newline = False)
                if elm.find('cropsstatus').text == '3':
                    self.logging(u'需犁地', timestamp = False)
                elif re.search(u"距离收获", elm.find('crops').text):
                    self.logging( re.search(u"(?P<output>距离收获.*)<", elm.find('crops').text).group('output'), timestamp = False)
                else:
                    self.logging(strip_html_tags(elm.find('crops').text), timestamp = False)

    def readMyranch(self):
        if self.event.isSet():
            return
        try:
            self.logging(u'获取Verify...', newline = False)
            a = ranchVerify()
            self.logging(u'成功', timestamp = False)
        except:
            self.logging(u'失败', timestamp = False)
            return
        self.verify = a[0]
        self.myuid = a[1]
        if self.event.isSet():
            return
        self.logging(u'读取牧场信息...', newline = False)
        r = self.getconf_ranch('0')
        if not r:
            self.logging(u'失败', timestamp = False)
            return
        else:
            self.logging(u'成功', timestamp = False)
        for elm in r.findall('account'):
            self.logging( elm.find('name').text + ' ' + elm.find('ranktip').text.replace('\n',''))
            self.logging( elm.find('cashtip').text + ' '+
                    u'魅力值'+ ' ' + elm.find('tcharms').text)
        self.logging( strip_html_tags(r.find('watertips').text) )
        self.logging( strip_html_tags(r.find('grasstips').text) )
        animals = r.findall('animals/item')
        for elm in animals:
            self.logging( elm.find('aname').text +'(' +elm.find('animalsid').text+')')
            self.logging( strip_html_tags(elm.find('tips').text) )
        if len( r.find('product2') ) > 0:
            for elm in r.findall('product2/item'):
                self.logging( elm.find('pname').text + strip_html_tags(elm.find('tips').text))

    def runMygarden(self):
        if self.event.isSet():
            return
        try:
            self.logging(u'获取Verify...', newline = False)
            a = gardenVerify()
            self.logging(u'成功', timestamp = False)
        except:
            self.logging(u'失败', timestamp = False)
            return
        self.verify = a[0]
        self.myuid = a[1]
        if self.event.isSet():
            return
        self.logging(u'读取菜地信息...', newline = False)
        r = self.getconf_garden('0')
        if not r:
            self.logging(u'失败', timestamp = False)
            return
        else:
            self.logging(u'成功', timestamp = False)
        userid = '0'
        myaccount = {}
        myaccount['name'] = r.find('account/name').text
        myaccount['rank'] = r.find('account/ranktip').text.replace('\n','')
        myaccount['cash'] = r.find('account/cashtip').text
        myaccount['charm'] = r.find('account/tcharms').text
        self.logging( myaccount['name'] + ' ' + myaccount['rank'] )
        self.logging( myaccount['cash'] + ' '+ u'魅力值'+ ' ' + myaccount['charm'])
        allitem = r.findall('garden/item')
        needseeds = 0
        myfields = [elm for elm in allitem if elm.find('status').text == '1' and elm.find('shared').text == '0']
        if self.seeding:
            self.logging(u'自动播种已开启，预设种子为<'+self.autoseedname+'>')
            for elm in myfields:
                if elm.find('cropsid').text == '0' or elm.find('cropsstatus').text in ['-1','3','2']:
                    needseeds = needseeds + 1
            if needseeds > 0:
                self.autoseed(self.autoseedid, needseeds)
        
        for elm in myfields:
            if self.event.isSet():
                return
            if elm.find('cropsid').text == '0':
                if self.seeding:
                    self.logging(u'在<'+myaccount['name']+u'>家'+elm.find('farmnum').text+u'号地播种<' + self.autoseedname +'>...', newline = False)
                    if self.farmseed( elm.find('farmnum').text, self.autoseedid ):
                        self.logging(u'成功', timestamp = False)
                    else:    
                        self.logging(u'失败', timestamp = False)
                
            if elm.find('cropsid').text != '0':
                if elm.find('cropsstatus').text in ['-1','3']:
                    self.logging(u'在<'+myaccount['name']+u'>家'+elm.find('farmnum').text+u'号地犁地...', newline = False)
                    if self.plough(elm.find('farmnum').text,'0'):
                        self.logging(u'成功', timestamp = False)
                        #Autoseed
                        if self.seeding:
                            self.logging(u'在<'+myaccount['name']+u'>家'+elm.find('farmnum').text+u'号地播种<' + self.autoseedname +'>...', newline = False)
                            if self.farmseed( elm.find('farmnum').text, self.autoseedid ):
                                self.logging(u'成功', timestamp = False)
                            else:    
                                self.logging(u'失败', timestamp = False)
                    else:    
                        self.logging(u'失败', timestamp = False)
                elif elm.find('cropsstatus').text == '2':
                    self.logging(u'在<'+myaccount['name']+u'>家'+elm.find('farmnum').text+u'号地收获...', newline = False)
                    harvestSucc = self.harvest_garden(elm.find('farmnum').text,userid)
                    if not harvestSucc['ret']:
                        self.logging(harvestSucc['status'], timestamp = False)
                    else:
                        self.logging(harvestSucc['status'], timestamp = False)
                        self.logging(u'在<'+myaccount['name']+u'>家'+elm.find('farmnum').text+u'号地犁地...', newline = False)
                        if self.plough(elm.find('farmnum').text,'0'):
                            self.logging(u'成功', timestamp = False)
                            #Autoseed                
                            if self.seeding:
                                self.logging(u'在<'+myaccount['name']+u'>家'+elm.find('farmnum').text+u'号地播种<' + self.autoseedname +'>...', newline = False)
                                if self.farmseed( elm.find('farmnum').text, self.autoseedid ):
                                    self.logging(u'成功', timestamp = False)
                                else:    
                                    self.logging(u'失败', timestamp = False)
                        else:    
                            self.logging(u'失败', timestamp = False)
        for elm in allitem:#开始日常护理
            if self.event.isSet():
                return
            if elm.find('status').text == '1':
                for elme in self.me_actionsList:
                    if elme['check'](elm):
                        cleanSucc = self.cleaning(elme['url'], elm.find('farmnum').text,userid,elme['method'])
                        if cleanSucc:
                            self.logging(u'在<' + myaccount['name'] + u'>家的'+elm.find('farmnum').text+u'号地'+elme['action'])

    def runMyranch(self):
        if self.event.isSet():
            return
        try:
            self.logging(u'获取Verify...', newline = False)
            a = ranchVerify()
            self.logging(u'成功', timestamp = False)
        except:
            self.logging(u'失败', timestamp = False)
            return
        self.verify = a[0]
        self.myuid = a[1]
        if self.event.isSet():
            return
        self.logging(u'读取牧场信息...', newline = False)
        r = self.getconf_ranch('0')
        if not r:
            self.logging(u'失败', timestamp = False)
            return
        else:
            self.logging(u'成功', timestamp = False)
        userid = '0'
        myaccount = {}
        myaccount['name'] = r.find('account/name').text
        myaccount['rank'] = r.find('account/ranktip').text.replace('\n','')
        myaccount['cash'] = r.find('account/cashtip').text
        myaccount['charm'] = r.find('account/tcharms').text
        self.logging( myaccount['name'] + ' ' + myaccount['rank'] )
        self.logging( myaccount['cash'] + ' '+ u'魅力值'+ ' ' + myaccount['charm'])
        self.logging( strip_html_tags(r.find('watertips').text) )
        self.logging( strip_html_tags(r.find('grasstips').text) )
        if int(r.find('water').text) < 51:
            self.logging(u'在' + myaccount['name'] + u'家添水...', newline = False)
            waterSucc = self.water_ranch(userid)
            if waterSucc == False:
                self.logging(u'失败', timestamp = False)
            else:
                self.logging(u'成功', timestamp = False)
                self.logging(waterSucc)
        if int(r.find('grass').text) < 151:
            self.autofood('63','0')

        if len( r.find('product2') ) > 0:
            stealable = r.findall('product2/item')
            for elm in stealable:
                if self.event.isSet():
                    return
                self.logging( elm.find('pname').text + strip_html_tags(elm.find('tips').text) + u'，开始收获...', newline = False )
                harvestSucc = self.harvest_ranch(userid, elm.find('skey').text, elm.find('type').text)
                if harvestSucc == False:
                    self.logging(u'失败', timestamp = False)
                else:
                    self.logging(u'收获' + harvestSucc + u'个', timestamp = False)
                  
        allanimals = r.findall('animals/item')
        for elm in allanimals:
            if self.event.isSet():
                return
            self.logging(elm.find('aname').text+'(' +elm.find('animalsid').text+')')
            self.logging(strip_html_tags(elm.find('tips').text))
            #if elm.find('bproduct').text == '1':
            #if elm.find('bproduct').text == '-2':#产肉
            if elm.find('bproduct').text == '2':
                self.logging(u'将' + myaccount['name'] + u'的 ' + elm.find('aname').text +'(' +elm.find('animalsid').text+')'+ u' 赶去生产...', newline = False)
                productSucc = self.product(userid, elm.find('animalsid').text)
                if productSucc == False:
                    self.logging(u'失败', timestamp = False)
                else:
                    self.logging(u'成功', timestamp = False)
                    self.logging(productSucc)

    def getconf_garden(self, fuid):
        req = httprequest.openurl(
                'http://www.kaixin001.com/!house/!garden//getconf.php',
                {'verify':self.verify, 'fuid':fuid}, 
                'Get'
                )
        try:
            r = ET.fromstring(req['data'])
        except xml.parsers.expat.ExpatError:
            return False
        return r

    def getconf_ranch(self, fuid):
        req = httprequest.openurl(
                'http://www.kaixin001.com/!house/!ranch//getconf.php',
                {'verify':self.verify, 'fuid':fuid},
                'Get'
                )
        try:
            r = ET.fromstring(req['data'])
        except:
            return False
        return r

    def friends_list(self, choice):
        if not config.global_friends_choice:
            result = getAllFriend()
        elif choice == 'garden':
            result = self.getfriendmature_list()
        elif choice == 'ranch':
            result = self.getfriendproduct2_list()
        return result

    def smartc(self):
        req = httprequest.openurl(
                'http://www.kaixin001.com/!house/!garden/smartc.php',{'verify':self.verify,'fuid':'0'},'Get')

    def getpic(self):
        req = httprequest.openurl(
                'http://www.kaixin001.com/house/garden/smartq.php',{'verify':self.verify},'Get')
        #f = open(str(time.time())+'.png','wb')
        cc=time.localtime()
        filename = str(cc[0])+str(cc[1])+str(cc[2])+str(cc[3])+str(cc[4])+str(cc[5])+'.png' 
        f = open(filename,'wb')
        f.write(req['data'])
        f.close()
        return filename

    def smarta(self,order):
        url = 'http://www.kaixin001.com/!house/!garden/smarta.php'
        param = { 'verify':self.verify, 'ordernum':order }
        req = httprequest.openurl(url, param, 'Get')
        try:
            r = ET.fromstring(req['data'])
        except xml.parsers.expat.ExpatError:
            return False
        if r.find('ret').text == 'succ':
            return True


    def friends_garden(self):
        if self.event.isSet():
            return
        try:
            self.logging(u'获取Verify...', newline = False)
            a = gardenVerify()
            self.logging(u'成功', timestamp = False)
        except:
            self.logging(u'失败', timestamp = False)
            return
        self.verify = a[0]
        self.myuid = a[1]
        if self.event.isSet():
            return
        self.logging(u'读取好友列表...', newline = False)
        try:
            userlist = self.friends_list('garden')
            self.logging(u'成功', timestamp = False)
        except:
            self.logging(u'失败', timestamp = False)
            return
        for item in userlist:
            if self.event.isSet():
                return
            userid = item
            username = userlist[item]
            self.logging(u'偷窥<'+username+u'>家的花园...', newline = False)
            try:
                r = self.getconf_garden(userid)
                if not r:
                    self.logging(u'失败', timestamp = False)
                    continue
                else:
                    self.logging(u'成功', timestamp = False)
            except:    
                continue
            allitem = r.findall('garden/item')
            for elm in allitem:
                #self.smartc()
                #self.getpic()
                try:
                    assert r.find('account/careurl').text == None
                except:
                    self.logging(u'发现菜老伯！下次再偷。')
                    break
                if self.event.isSet():
                    return
                if elm.find('status').text == '1' and elm.find('shared').text == '0' and elm.find('cropsid').text != '0':
                    if elm.find('crops') == None:
                        pass
                    elif re.search(u'已偷过' , elm.find('crops').text):
                        self.logging( u'<%s>家%s号地<%s>已偷过'%(username,elm.find('farmnum').text,elm.find('name').text) )
                    elif re.search(u'可偷' , elm.find('crops').text):#保护期
                        self.logging(u'<%s>家%s号地<%s>%s'%(username,elm.find('farmnum').text,elm.find('name').text,strip_html_tags(elm.find('crops').text) ))
                    elif elm.find('cropsstatus').text == '2' and elm.find('seedid').text not in config.global_steallist:
                        self.logging(u'<%s>家%s号地<%s> 跳过'%(username,elm.find('farmnum').text,elm.find('name').text))
                    elif re.search(u'剩余：1<' , elm.find('crops').text):
                        self.logging(u'<%s>家%s号地还剩1个<%s>，放ta一马吧'%(username,elm.find('farmnum').text,elm.find('name').text))
                    elif re.search(u'已偷光' , elm.find('crops').text):
                        pass
                    elif elm.find('cropsstatus').text == '2':#开始偷
                        smart_flag = False
                        while not smart_flag:
                            self.logging(u'在<%s>家%s号地偷...'%(username,elm.find('farmnum').text), newline = False)
                            harvestSucc = self.harvest_garden(elm.find('farmnum').text,userid)
                            if not harvestSucc['ret']:
                                self.logging(harvestSucc['status'], timestamp = False)
                                smart_flag = True
                            elif harvestSucc['status'] == 'smart':
                                self.logging(u'遇到花园精灵', timestamp = False)
                                if self.event.isSet():
                                    return
                                smart_count = 1
                                self.logging(u'获取精灵问题')
                                self.smartc()
                                self.logging(u'获取精灵图片')
                                im_name = self.getpic()
                                self.logging(u'开始识别图片')
                                smart_order = readcaptcha(im_name)
                                order = ','+','.join( [i[1]['id'] for i in smart_order] )
                                if self.smarta(order):
                                    self.logging(u'回答成功')
                                    os.remove(im_name)
                                else:
                                    self.logging(u'回答失败')
                                    smart_count += 1
                                    if smart_count > 3:
                                        smart_flag = True
                            else:
                                self.logging(u'偷到' + harvestSucc['status'], timestamp = False)
                                smart_flag = True

            for elm in allitem:
                if self.event.isSet():
                    return
                if elm.find('status').text == '1':
                    #开始清扫
                    for elme in self.friends_actionsList:
                        if elme['check'](elm):
                            self.logging(u'给<%s>家的%s号地%s...'%(username,elm.find('farmnum').text,elme['action']), newline = False)
                            cleanSucc = self.cleaning(elme['url'], elm.find('farmnum').text,userid,elme['method'])
                            if cleanSucc:
                                self.logging(u'成功', timestamp = False)
                            else:
                                self.logging(u'失败', timestamp = False)

    def friends_ranch(self):
        if self.event.isSet():
            return
        try:
            self.logging(u'获取Verify...', newline = False)
            a = ranchVerify()
            self.logging(u'成功', timestamp = False)
        except:
            self.logging(u'失败', timestamp = False)
            return
        self.verify = a[0]
        self.myuid = a[1]
        if self.event.isSet():
            return
        self.logging(u'读取好友列表...', newline = False)
        try:
            userlist = self.friends_list('ranch')
            self.logging(u'成功', timestamp = False)
        except:
            self.logging(u'失败', timestamp = False)
            return

        for item in userlist:
            if self.event.isSet():
                return
            userid = item
            username = userlist[item]
            self.logging(u'偷窥<'+username+u'>家的牧场...', newline = False)
            r = self.getconf_ranch(userid)
            if r == False:
                self.logging(u'失败', timestamp = False)
                continue
            self.logging(u'成功', timestamp = False)
            if len( r.find('product2') ) > 0:
                stealable = r.findall('product2/item')
                for elm in stealable:
                    try:
                        assert r.find('account/policeurl').text == None
                    except:
                        self.logging(u'发现警察蜀黍！下次再偷。')
                        break
                    if self.event.isSet():
                        return
                    if re.search(u'下次可偷' , elm.find('tips').text):
                        self.logging(u'<'+username+u'>家的<' + elm.find('pname').text+ u'>已偷过 '+ strip_html_tags(elm.find('tips').text))
                    elif elm.find('skey').text not in config.global_steallist_ranch:
                        self.logging(u'<'+username+u'>家的<' + elm.find('pname').text+ u'>跳过')                        
                    else:
                        self.logging( elm.find('pname').text + strip_html_tags(elm.find('tips').text) + u'，开始偷...', newline = False )
                        harvestSucc = self.harvest_ranch(userid, elm.find('skey').text, elm.find('type').text)
                        if harvestSucc == False:
                            self.logging(u'失败', timestamp = False)
                        else:
                            self.logging(u'偷到' + harvestSucc + u'个', timestamp = False)
                
            allanimals = r.findall('animals/item')
            for elm in allanimals:
                if self.event.isSet():
                    return
                self.logging(elm.find('aname').text +'(' +elm.find('animalsid').text+')')
                self.logging(strip_html_tags(elm.find('tips').text))
                #if elm.find('bproduct').text == '1':
                if elm.find('bproduct').text == '2':
                    self.logging(u'将' + username + u'的 ' + elm.find('aname').text +'(' +elm.find('animalsid').text+')'+ u' 赶去生产...', newline = False)
                    productSucc = self.product(userid, elm.find('animalsid').text)
                    if productSucc == False:
                        self.logging(u'失败', timestamp = False)
                    else:
                        self.logging(u'成功', timestamp = False)
                        self.logging(productSucc)

    def product(self, uid, animalsid):
        param = {
                'verify':self.verify,
                'animalsid':animalsid,
                'fuid':uid
                }
        req = httprequest.openurl(
                'http://www.kaixin001.com/!house/!ranch//product.php',param)
        try:
            r = ET.fromstring(req['data'])
        except xml.parsers.expat.ExpatError:
            return False
        if r.find('ret').text == 'succ':
            message = (strip_html_tags(r.find('tips').text))
            return message
        else:
            return False

    def getfriendmature(self):
        req = httprequest.openurl(
            'http://www.kaixin001.com/!house/!garden/getfriendmature.php',
            {'verify':self.verify},'Get')
        data = json.loads(req['data'])
        return data

    def getShared(self):
        r = self.getfriendmature()
        result = {}
        if r['share']:
            for elm in r['share']:
                result[ elm['uid'] ] = elm['realname']
        if r['friend']:
            for elm in r['friend']:
                if elm['blove']:
                    result[ elm['uid'] ] = elm['realname']

        return result

    def getfriendmature_list(self):
        result = {}
        r = self.getfriendmature()
        friendmature = r['share'] + r['friend']
        if len(friendmature) > 0:
            for elm in friendmature:
                result[ elm['uid'] ] = elm['realname']
        return result
            
    def getfriendproduct2(self):
        req = httprequest.openurl(
            'http://www.kaixin001.com/!house/!ranch//getfriendproduct2.php',
            {'verify':self.verify}, 'Get')
        data = json.loads(req['data'])
        return data['steal'] + data['product']
    
    def getfriendproduct2_list(self):
        result = {}
        friendmature = self.getfriendproduct2()
        if len(friendmature) > 0:
            for elm in friendmature:
                result[ elm['uid'] ] = elm['realname']
        return result
            
    def cleaning(self, url, fieldnum, uid, method):
        param = {
                'verify':self.verify,
                'farmnum':fieldnum,
                'fuid':uid
                }
        req = httprequest.openurl(url,param,method)
        try:
            r = ET.fromstring(req['data'])
        except xml.parsers.expat.ExpatError:
            return False
        if r.find('ret').text == 'succ':
            return True

    def harvest_garden(self, fieldnum, uid):
        url = 'http://www.kaixin001.com/!house/!garden/havest.php'
        param = {
                'verify':self.verify,
                'farmnum':fieldnum,
                'fuid':uid
                }
        req = httprequest.openurl(url, param, 'Get')
        result = {}
        try:
            r = ET.fromstring(req['data'])
        except xml.parsers.expat.ExpatError:
            result['ret'] = False
            result['status'] = u'连接失败'
            return result
        
        result['ret'] = True if r.find('ret').text == 'succ' else False
        if result['ret']:    
            if r.find('anti') != None:
                if r.find('anti').text == '1':
                    result['status'] = 'smart'
                elif r.find('stealnum').text:
                    result['status'] = r.find('stealnum').text + u'个' + r.find('seedname').text
            else:
                result['status'] = r.find('num').text + u'个' + r.find('seedname').text
        else:
            result['status'] = r.find('reason').text
        return result
    
    def harvest_ranch(self, uid, skey, type):
        param = {
                'verify':self.verify,
                'foodnum':'1',
                'skey':skey,
                'type':type,
                'fuid':uid
                }
        req = httprequest.openurl(
                'http://www.kaixin001.com/!house/!ranch//havest.php',param,'Get')
        try:
            r = ET.fromstring(req['data'])
        except xml.parsers.expat.ExpatError:
            return False
        if r.find('ret').text == 'succ':
            message = r.find('num').text
            return message 
        else:
            return False
    
    def plough(self, fieldnum, uid):
        param = {
                'verify':self.verify,
                'farmnum':fieldnum,
                'fuid':uid
                }
        req = httprequest.openurl(
                'http://www.kaixin001.com/!house/!garden/plough.php',param,'Get')
        try:
            r = ET.fromstring(req['data'])
        except xml.parsers.expat.ExpatError:
            return False

        if r.find('ret').text == 'succ':
            return True
        else:
            return False

    def autoseed(self, autoseedid, needseeds):
        existseednum = 0
        self.logging(u'读取现有种子...')
        req = httprequest.openurl(
                'http://www.kaixin001.com/!house/!garden/myseedlist.php',
                {'verify':self.verify
                    ,'page':1
                    },
                'Get'
                )
        myseeds = req['data']
        try:
            r = ET.fromstring(myseeds)
        except xml.parsers.expat.ExpatError:
            pass
        totalpage = r.find('totalpage').text
        if totalpage == '0':
            buynum = needseeds
        elif int( totalpage ) > 1:
            for i in range(2, int(totalpage)+1):
                        req = httprequest.openurl(
                                'http://www.kaixin001.com/!house/!garden/myseedlist.php',
                                {'verify':self.verify
                                    ,'page':i
                                    },
                                'Get'
                                )
                        myseeds = myseeds + req['data']
            myseeds = '<root>'+myseeds+'</root>'
            r = ET.fromstring(myseeds)
        for elm in r.findall('.//seed/item'):
            if elm.find('seedid').text == autoseedid:
                existseednum = int(elm.find('num').text)
            if needseeds - existseednum > 0:
                buynum = needseeds - existseednum
            else:
                buynum = 0
        if buynum > 0:
            self.logging(u'买种子...' + str(buynum) + u'个', newline = False)
            if self.buyseed( autoseedid, buynum ):
                self.logging(u'成功', timestamp = False)
            else:
                self.logging(u'失败', timestamp = False)

    def buyseed(self, seedid, num):
        param = {
                'verify':self.verify,
                'seedid':seedid,
                'num':num
                }
        req = httprequest.openurl(
                'http://www.kaixin001.com/!house/!garden//buyseed.php',param)
        try:
            r = ET.fromstring(req['data'])
        except xml.parsers.expat.ExpatError:
            return False

        if r.find('ret').text == 'succ':
            return True
        else:
            return False

    def farmseed(self, fieldnum, seedid):
        param = {
                'verify':self.verify,
                'farmnum':fieldnum,
                'seedid':seedid
                }
        req = httprequest.openurl(
                'http://www.kaixin001.com/!house/!garden/farmseed.php',param,'Get')
        try:
            r = ET.fromstring(req['data'])
        except xml.parsers.expat.ExpatError:
            return False

        if r.find('ret').text == 'succ':
            return True
        else:
            return False

    def water_ranch(self, uid):
        param = {
                'verify':self.verify,
                'foodnum':'1',
                'fuid':uid
                }
        req = httprequest.openurl(
                'http://www.kaixin001.com/!house/!ranch//water.php',param)
        try:
            r = ET.fromstring(req['data'])
        except xml.parsers.expat.ExpatError:
            return False

        if r.find('ret').text == 'succ':
            return strip_html_tags(r.find('watertips').text)
        else:
            return False

    def autofood(self, autofoodid, uid):
        self.logging(u'读取现有饲料...')
        req = httprequest.openurl(
                'http://www.kaixin001.com/!house/!ranch//foodlist.php',
                {'verify':self.verify
                    ,'page':1
                    }
                )
        myseeds = req['data']
        try:
            r = ET.fromstring(myseeds)
        except xml.parsers.expat.ExpatError:
            self.logging(u'读取失败...')
            return
        totalpage = r.find('totalpage').text
        foodnum = ''
        if totalpage == '0':
            self.logging(u'注意！没有饲料了！')
            return
        elif int( totalpage ) > 1:
            for i in range(2, int(totalpage)+1):
                        req = httprequest.openurl(
                                'http://www.kaixin001.com/house/ranch//foodlist.php',
                                {'verify':self.verify
                                    ,'page':i
                                    }
                                )
                        myseeds = myseeds + req['data']
            myseeds = '<root>'+myseeds+'</root>'
            r = ET.fromstring(myseeds)
        for elm in r.findall('.//food/item'):
            if elm.find('seedid').text == autofoodid:
                if int(elm.find('num').text) > 199:
                    foodnum = '200'
                else:
                    foodnum = elm.find('num').text
                self.logging(u'现存牧草...' + elm.find('num').text + u'个')
        if not foodnum:
            self.logging(u'没有存粮了...')
            return
        self.logging(u'添草...' + foodnum + u'个', newline = False)
        if self.food( foodnum, autofoodid, uid):
            self.logging(u'成功', timestamp = False)
        else:
            self.logging(u'失败', timestamp = False)

    def food(self, foodnum, seedid, uid):
        param = {
                'verify':self.verify,
                'foodnum':foodnum,
                'fuid':uid,
                'type':'0',
                'seedid':seedid
                }
        req = httprequest.openurl(
                'http://www.kaixin001.com/!house/!ranch//food.php',param)
        try:
            r = ET.fromstring(req['data'])
        except xml.parsers.expat.ExpatError:
            return False

        if r.find('ret').text == 'succ':
            return True
        else:
            return False

    def stop(self):
        self.event.set()

    def readMyfishing(self):
        if self.event.isSet():
            return
        try:
            self.logging(u'获取Verify...', newline = False)
            a = fishingVerify()
            self.logging(u'成功', timestamp = False)
        except:
            self.logging(u'失败', timestamp = False)
            return
        self.verify = a[0]
        self.myuid = a[1]
        self.logging(u'读取鱼塘信息...', newline = False)
        r = self.getconf_fishing('0')
        if not r:
            self.logging(u'失败', timestamp = False)
            return
        else:
            self.logging(u'成功', timestamp = False)
        for elm in r.findall('account'):
            self.logging( elm.find('title').text + ' ' + strip_html_tags(elm.find('ranktips').text) + elm.find('cashtips').text)
            self.logging(strip_html_tags(elm.find('fishtips').text))
        for elm in r.findall('fish/item'):
            self.logging( elm.find('fishid').text + ' ' + strip_html_tags(replaceCharEntity(elm.find('tips').text)).replace('\n',','))

    def getconf_fishing(self, fuid):
        req = httprequest.openurl(
                'http://www.kaixin001.com/!fish/!getconf.php',
                {'verify':self.verify, 'fuid':fuid}, 
                'Post'
                )
        try:
            r = ET.fromstring(req['data'])
        except xml.parsers.expat.ExpatError:
            return False
        return r


